/*
 * Copyright (c) 2022, yifengling0. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. No personal names or organizations' names associated with the
 *    Atomthreads project may be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE ATOMTHREADS PROJECT AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "atom.h"
#include "mraa/spi.h"
#define ATOM_NONE_STANDARDIO
#include "drv_pin.h"
#include "drv_spi.h"

#define SPI_BUS (0)

static int upboardSpiXfer(SpiBase* dev, const void* send_buf, void* recv_buf, size_t length)
{
    UpboardSpi* pDrv = (UpboardSpi*)dev;

    if (pDrv->Protected.autoCs) {
        PinWrite(pDrv->Protected.csPin, PIN_LOW);
    }

    mraa_result_t result = mraa_spi_transfer_buf((mraa_spi_context)pDrv->Protected.context, send_buf, recv_buf, length);

    if (pDrv->Protected.autoCs) {
        PinWrite(pDrv->Protected.csPin, PIN_HIGH);
    }

    return MRAA_SUCCESS == result;
}

void UpSpiCreate(UpboardSpi* dev, const char* name, uint32_t freq, int mode, int dataLines, int cpol, int cpha, int bitwidth)
{
    dev->Protected.autoCs = 0;

    if (dev->Protected.autoCs) {
        PinMode(dev->Protected.csPin, PIN_MODE_OUTPUT);
    }
    
    mraa_spi_context context = mraa_spi_init(SPI_BUS);
    dev->Protected.context = (POINTER)context;

    mraa_spi_mode(context, (mraa_spi_mode_t)((cpol << 1) | cpha));
    mraa_spi_frequency(context, freq);
    mraa_spi_bit_per_word(context, bitwidth);
    mraa_spi_lsbmode(context, mode == SPI_LSB_FIRST ? 1 : 0);

    SpiCreate(&dev->Super, name, mode, dataLines, cpol, cpha, bitwidth, freq, upboardSpiXfer);
}